<?php

namespace app\admin\controller;

use classes\RedisClass;
use classes\TokenBucket;
use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Log;

/**
 * 资讯管理
 */
class Article extends BasicAdmin
{

    public $article = 'tp_article';
    public $cate = 'tp_article_cate';

    /**
     * 列表
     * @return array|string
     */
    public function lists()
    {

        $get = $this->request->get();
        $db = Db::name($this->article)
            ->alias('a')
            ->join($this->cate . ' b', 'b.cate_id=a.cate_id', 'left')
            ->field('a.*,b.name cate_name');

        foreach (['article_id', 'title'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->whereLike('a.' . $field, "%{$value}%");
            }
        }
        foreach (['cate_id'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->where('a.' . $field, "{$value}");
            }
        }
        //分类
        $cates = Db::name($this->cate)
            ->order('sort desc,cate_id asc')
            ->select();


        foreach (['create_at'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                list($start, $end) = explode(' - ', $get[$field]);
                $db->whereTime($field, ["{$start} 00:00:00", "{$end} 23:59:59"]);
            }
        }

        $order = 'a.article_id desc';
        $this->assign('cates', $cates);
        return parent::_list($db->order($order), 'article_id');
    }


    /**
     * 添加
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        if (!$this->request->isPost()) {
            $this->title = '添加';
            $cateField = 'cate_id,name';
            $cates = Db::name($this->cate)->field($cateField)->order('sort asc,cate_id asc')->select();
            $this->assign('cates', $cates);
            return $this->_form($this->article, 'form');
        }
        try {
            $data = $this->request->post();
            Db::transaction(function () use ($data) {
                if (!empty($data['video_url'])) {
                    //视频截帧（cos配置工作流）
                    $url_arr = explode('http://jtyhvideo.zoudingyong.com', $data['video_url']);
                    $url_arr = explode('.', $url_arr[1]);
                    $small_pic = 'http://jtyhvideo.zoudingyong.com' . $url_arr[0] . '_0.jpg';
                    $data['small_pic'] = $small_pic;
                }

                Db::name($this->article)->insert($data);
            });


        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('添加失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('article/lists')];
        $this->success('添加成功！', "{$base}#{$url}?spm={$spm}");
    }

    /**
     * 编辑
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $article = Db::name($this->article)->where(['article_id' => $id])->find();
            empty($article) && $this->error('需要编辑的不存在！');
            $cateField = 'cate_id,name';
            //赛区
            $cates = Db::name($this->cate)->field($cateField)->order('sort asc,cate_id asc')->select();
            $this->assign('cates', $cates);
            return $this->fetch('form', ['vo' => $article, 'title' => '编辑']);
        }
        try {
            $data = $this->request->post();
            $id = $this->request->post('id');
            $article = Db::name($this->article)->where(['article_id' => $id])->find();
            empty($article) && $this->error('编辑失败，请稍候再试！');

            Db::transaction(function () use ($data, $id, $article) {

                if (empty($article['small_pic']) && !empty($data['video_url'])) {
                    //视频截帧（cos配置工作流）
                    $url_arr = explode('http://jtyhvideo.zoudingyong.com', $data['video_url']);
                    $url_arr = explode('.', $url_arr[1]);
                    $small_pic = 'http://jtyhvideo.zoudingyong.com' . $url_arr[0] . '_0.jpg';
                    $data['small_pic'] = $small_pic;
                }

                $where = ['article_id' => $id];
                unset($data['article_id']);
                Db::name($this->article)->where($where)->update($data);

            });


        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('article/lists')];


        $this->success('编辑成功！', "{$base}#{$url}?spm={$spm}");
    }


    /**
     * 删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->article)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }


}
